import { _decorator, Vec3 } from 'cc';
import { BaseSkill } from './BaseSkill';
import { CharacterController } from '../controllers/CharacterController';
import { EvolutionSkills } from '../config/EvolutionConfig';
import { JoystickController } from '../core/JoystickController';

const { ccclass, property } = _decorator;

@ccclass('FlySkill')
export class FlySkill extends BaseSkill {
    @property(CharacterController)
    private characterController: CharacterController | null = null;

    private originalSpeed: number = 0;
    private currentHeight: number = 0;
    private readonly flySpeedBoost: number = EvolutionSkills.fly.flySpeedBoost;
    private readonly maxHeight: number = EvolutionSkills.fly.maxHeight;
    private readonly heightChangeSpeed: number = 5;

    private heightTarget: number = 0;

    update(deltaTime: number) {
        super.update(deltaTime);
        if (this.isActive) {
            this.updateFlight(deltaTime);
        }
    }

    private updateFlight(deltaTime: number) {
        if (!this.characterController) return;

        // 获取垂直方向输入
        const input = JoystickController.instance.getMoveDirection();
        this.heightTarget = Math.max(0, Math.min(this.maxHeight, 
            this.currentHeight + input.y * this.heightChangeSpeed * deltaTime));

        // 平滑过渡到目标高度
        this.currentHeight = this.lerp(this.currentHeight, this.heightTarget, deltaTime * 5);

        // 更新角色高度
        const pos = this.node.position;
        pos.y = this.currentHeight;
        this.node.setPosition(pos);
    }

    private lerp(start: number, end: number, t: number): number {
        return start + (end - start) * t;
    }

    protected onActivate(): void {
        if (!this.characterController) return;

        this.originalSpeed = this.characterController.moveSpeed;
        this.characterController.moveSpeed *= this.flySpeedBoost;

        // 记录当前高度
        this.currentHeight = this.node.position.y;
        this.heightTarget = this.currentHeight;
    }

    protected onDeactivate(): void {
        if (!this.characterController) return;
        
        this.characterController.moveSpeed = this.originalSpeed;

        // 平滑降落
        this.heightTarget = 0;
    }

    // 获取当前飞行高度的百分比
    public getHeightPercentage(): number {
        return this.currentHeight / this.maxHeight;
    }
} 